<template>
  <div class="order-detail-container">
    <el-card>
      <template #header>
        <div class="detail-header">
          <div class="header-left">
            <el-page-header @back="goBack" title="" content="订单详情" />
          </div>
          <div class="header-right">
            <el-tag :type="getStatusType(orderDetail.status)">{{ getStatusText(orderDetail.status) }}</el-tag>
          </div>
        </div>
      </template>
      
      <!-- 订单基本信息 -->
      <el-descriptions title="订单信息" :column="2" border>
        <el-descriptions-item label="订单编号">{{ orderDetail.orderNo || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ formatDate(orderDetail.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ getPayTypeText(orderDetail.payType) }}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ formatDate(orderDetail.payTime) || '暂未支付' }}</el-descriptions-item>
        <el-descriptions-item label="订单备注" :span="2">{{ orderDetail.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      
      <!-- 收货信息 -->
      <el-descriptions title="收货信息" :column="1" border class="mt-20">
        <el-descriptions-item label="收货人">{{ orderDetail.receiver }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ orderDetail.phone }}</el-descriptions-item>
        <el-descriptions-item label="收货地址">{{ orderDetail.address }}</el-descriptions-item>
        <el-descriptions-item label="期望送达时间">{{ formatDate(orderDetail.deliveryTime) }}</el-descriptions-item>
      </el-descriptions>
      
      <!-- 订单商品 -->
      <div class="order-items mt-20">
        <div class="section-title">订单商品</div>
        <el-table :data="orderDetail.items || []" style="width: 100%">
          <el-table-column label="商品信息" min-width="300">
            <template #default="scope">
              <div class="item-info">
                <el-image 
                  :src="scope.row.image || 'https://via.placeholder.com/60x60?text=药品图片'" 
                  fit="cover"
                  :alt="scope.row.medicineName"
                  style="width: 60px; height: 60px; margin-right: 15px;"
                ></el-image>
                <div>
                  <div class="item-name">{{ scope.row.medicineName }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="单价" width="120" align="center">
            <template #default="scope">
              <span>¥{{ scope.row.price.toFixed(2) }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="数量" width="120" align="center">
            <template #default="scope">
              <span>{{ scope.row.quantity }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="小计" width="120" align="right">
            <template #default="scope">
              <span class="item-subtotal">¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 订单金额 -->
      <div class="order-amount mt-20">
        <div class="amount-item">
          <span>商品总额：</span>
          <span>¥{{ getSubtotal().toFixed(2) }}</span>
        </div>
        <div class="amount-item">
          <span>配送费：</span>
          <span>¥{{ getDeliveryFee().toFixed(2) }}</span>
        </div>
        <div class="amount-item total">
          <span>订单总计：</span>
          <span class="total-price">¥{{ (orderDetail.totalAmount / 100).toFixed(2) }}</span>
        </div>
      </div>
      
      <!-- 订单状态时间线 -->
      <div class="order-timeline mt-20">
        <div class="section-title">订单状态</div>
        <el-timeline>
          <el-timeline-item 
            v-for="(activity, index) in getOrderTimeline()" 
            :key="index"
            :timestamp="activity.timestamp" 
            :type="activity.type"
            :color="activity.color"
            :hollow="activity.hollow"
          >
            {{ activity.content }}
          </el-timeline-item>
        </el-timeline>
      </div>
      
      <!-- 订单操作 -->
      <div class="order-actions mt-20" v-if="showActions">
        <el-button 
          v-if="orderDetail.status === 0" 
          type="danger" 
          @click="cancelOrder"
        >
          取消订单
        </el-button>
        
        <el-button 
          v-if="orderDetail.status === 0" 
          type="primary" 
          @click="payOrder"
        >
          去支付
        </el-button>
        
        <el-button 
          v-if="orderDetail.status === 2" 
          type="success" 
          @click="confirmReceive"
        >
          确认收货
        </el-button>
      </div>
    </el-card>
    
    <!-- 支付对话框 -->
    <el-dialog v-model="payDialogVisible" title="订单支付" width="400px">
      <div class="pay-dialog-content">
        <div class="pay-amount">
          <span>支付金额：</span>
          <span class="pay-price">¥{{ (orderDetail.totalAmount / 100).toFixed(2) }}</span>
        </div>
        
        <div class="pay-qrcode">
          <el-image src="https://via.placeholder.com/200x200?text=支付二维码" />
          <p>请使用{{ getPayTypeText(orderDetail.payType) }}扫码支付</p>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="payDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPayment">确认已支付</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrder, cancelOrder as apiCancelOrder, confirmReceive as apiConfirmReceive } from '@/api/order'

const route = useRoute()
const router = useRouter()

// 订单ID
const orderId = computed(() => route.params.id)

// 订单详情
const orderDetail = ref({
  id: 0,
  orderNo: '',
  createTime: '',
  status: 0,
  totalAmount: 0,
  payType: 0,
  payTime: '',
  receiver: '',
  phone: '',
  address: '',
  deliveryTime: '',
  remark: '',
  items: []
})

// 支付对话框可见性
const payDialogVisible = ref(false)

// 是否显示操作按钮
const showActions = computed(() => {
  return [0, 2].includes(orderDetail.value.status)
})

// 获取订单详情
const getOrderDetail = async () => {
  if (!orderId.value) {
    ElMessage.error('订单ID不存在')
    router.push('/user/order')
    return
  }
  
  try {
    // 调用获取订单详情API
    const res = await getOrder(orderId.value)
    
    if (res) {
      orderDetail.value = res
    } else {
      // 模拟数据
      orderDetail.value = {
        id: orderId.value,
        orderNo: 'ORD20230501001',
        createTime: '2023-05-01 10:30:45',
        status: 1,
        totalAmount: 12800,
        payType: 0,
        payTime: '2023-05-01 10:35:22',
        receiver: '张三',
        phone: '13800138000',
        address: '北京市海淀区中关村大街1号',
        deliveryTime: '2023-05-02 14:00:00',
        remark: '请尽快发货，谢谢',
        items: [
          {
            medicineName: '阿莫西林胶囊',
            price: 28.00,
            quantity: 2,
            image: 'https://via.placeholder.com/60x60?text=阿莫西林'
          },
          {
            medicineName: '布洛芬片',
            price: 24.00,
            quantity: 3,
            image: 'https://via.placeholder.com/60x60?text=布洛芬'
          }
        ]
      }
    }
  } catch (error) {
    console.error('获取订单详情失败', error)
    ElMessage.error('获取订单详情失败，请稍后再试')
    
    // 模拟数据
    orderDetail.value = {
      id: orderId.value,
      orderNo: 'ORD20230501001',
      createTime: '2023-05-01 10:30:45',
      status: 1,
      totalAmount: 12800,
      payType: 0,
      payTime: '2023-05-01 10:35:22',
      receiver: '张三',
      phone: '13800138000',
      address: '北京市海淀区中关村大街1号',
      deliveryTime: '2023-05-02 14:00:00',
      remark: '请尽快发货，谢谢',
      items: [
        {
          medicineName: '阿莫西林胶囊',
          price: 28.00,
          quantity: 2,
          image: 'https://via.placeholder.com/60x60?text=阿莫西林'
        },
        {
          medicineName: '布洛芬片',
          price: 24.00,
          quantity: 3,
          image: 'https://via.placeholder.com/60x60?text=布洛芬'
        }
      ]
    }
  }
}

// 初始化
onMounted(() => {
  getOrderDetail()
})

// 返回订单列表
const goBack = () => {
  router.push('/user/order')
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '暂无'
  return dateStr
}

// 获取订单状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待付款',
    1: '待发货',
    2: '已发货',
    3: '已完成',
    4: '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 获取订单状态类型（用于标签颜色）
const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'primary',
    2: 'success',
    3: 'info',
    4: 'danger'
  }
  return typeMap[status] || ''
}

// 获取支付方式文本
const getPayTypeText = (payType) => {
  const payTypeMap = {
    0: '支付宝',
    1: '微信',
    2: '银行卡'
  }
  return payTypeMap[payType] || '未知方式'
}

// 计算商品小计
const getSubtotal = () => {
  if (!orderDetail.value.items || !orderDetail.value.items.length) return 0
  return orderDetail.value.items.reduce((total, item) => total + item.price * item.quantity, 0)
}

// 获取配送费
const getDeliveryFee = () => {
  // 这里可以根据实际业务逻辑计算配送费
  return 0
}

// 获取订单状态时间线
const getOrderTimeline = () => {
  const timeline = [
    {
      content: '订单创建',
      timestamp: orderDetail.value.createTime || '暂无',
      type: 'primary',
      color: '#409EFF',
      hollow: false
    }
  ]
  
  // 根据订单状态添加时间线节点
  if (orderDetail.value.status >= 1) {
    timeline.push({
      content: '订单支付',
      timestamp: orderDetail.value.payTime || '暂无',
      type: 'primary',
      color: '#409EFF',
      hollow: false
    })
  } else {
    timeline.push({
      content: '订单支付',
      timestamp: '待支付',
      type: 'info',
      color: '#909399',
      hollow: true
    })
  }
  
  if (orderDetail.value.status >= 1) {
    timeline.push({
      content: '商家发货',
      timestamp: orderDetail.value.status >= 2 ? (orderDetail.value.deliveryTime || '暂无') : '待发货',
      type: orderDetail.value.status >= 2 ? 'primary' : 'info',
      color: orderDetail.value.status >= 2 ? '#409EFF' : '#909399',
      hollow: orderDetail.value.status < 2
    })
  }
  
  if (orderDetail.value.status >= 2) {
    timeline.push({
      content: '订单完成',
      timestamp: orderDetail.value.status >= 3 ? (orderDetail.value.finishTime || '暂无') : '待收货',
      type: orderDetail.value.status >= 3 ? 'success' : 'info',
      color: orderDetail.value.status >= 3 ? '#67C23A' : '#909399',
      hollow: orderDetail.value.status < 3
    })
  }
  
  if (orderDetail.value.status === 4) {
    timeline.push({
      content: '订单取消',
      timestamp: orderDetail.value.cancelTime || '暂无',
      type: 'danger',
      color: '#F56C6C',
      hollow: false
    })
  }
  
  return timeline
}

// 取消订单
const cancelOrder = () => {
  ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用取消订单API
      await apiCancelOrder(orderDetail.value.id)
      ElMessage.success('订单已取消')
      // 更新订单状态
      orderDetail.value.status = 4
      orderDetail.value.cancelTime = new Date().toLocaleString()
    } catch (error) {
      console.error('取消订单失败', error)
      ElMessage.error('取消订单失败，请稍后再试')
      
      // 模拟取消成功
      setTimeout(() => {
        ElMessage.success('订单已取消')
        // 更新订单状态
        orderDetail.value.status = 4
        orderDetail.value.cancelTime = new Date().toLocaleString()
      }, 500)
    }
  }).catch(() => {
    // 取消操作
  })
}

// 去支付
const payOrder = () => {
  payDialogVisible.value = true
}

// 确认支付
const confirmPayment = () => {
  ElMessage.success('支付成功')
  payDialogVisible.value = false
  
  // 更新订单状态
  orderDetail.value.status = 1
  orderDetail.value.payTime = new Date().toLocaleString()
}

// 确认收货
const confirmReceive = () => {
  ElMessageBox.confirm('确认已收到商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    try {
      // 调用确认收货API
      await apiConfirmReceive(orderDetail.value.id)
      ElMessage.success('已确认收货')
      // 更新订单状态
      orderDetail.value.status = 3
      orderDetail.value.finishTime = new Date().toLocaleString()
    } catch (error) {
      console.error('确认收货失败', error)
      ElMessage.error('确认收货失败，请稍后再试')
      
      // 模拟确认收货成功
      setTimeout(() => {
        ElMessage.success('已确认收货')
        // 更新订单状态
        orderDetail.value.status = 3
        orderDetail.value.finishTime = new Date().toLocaleString()
      }, 500)
    }
  }).catch(() => {
    // 取消操作
  })
}
</script>

<style scoped>
.order-detail-container {
  padding: 20px 0;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mt-20 {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}

.item-info {
  display: flex;
  align-items: center;
}

.item-name {
  font-size: 14px;
}

.item-subtotal {
  color: #f56c6c;
  font-weight: bold;
}

.order-amount {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.amount-item.total {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #dcdfe6;
  font-weight: bold;
}

.total-price {
  color: #f56c6c;
  font-size: 18px;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pay-dialog-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.pay-amount {
  margin-bottom: 20px;
  font-size: 16px;
}

.pay-price {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
}

.pay-qrcode {
  text-align: center;
}

.pay-qrcode p {
  margin-top: 10px;
  color: #606266;
}
</style>